package com.llkj.qingnianguoxue.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.http.AnsynHttpRequest;
import com.llkj.qingnianguoxue.login.LoginActivity;
import com.llkj.qingnianguoxue.util.DialogUtil;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.Utils;

import org.json.JSONException;
import org.json.JSONObject;

@SuppressLint("NewApi")
public class BaseFragment extends Fragment implements AnsynHttpRequest.ObserverCallBack {
    private Dialog waitDialog;
    protected View rootView;
    protected Activity mActivity;
    protected LayoutInflater mInflater;
    protected RelativeLayout rlTitle;
    protected TextView tvTitle;
    protected LinearLayout llLeft, llRight;
    protected ImageView ivLeft, ivRight;
    protected TextView tvLeft, tvRight;
    protected View titleLineBottom;
    /**
     * 标记标题左右两边的类型:文字
     */
    protected final int TITLE_TYPE_TEXT = 0;
    /**
     * 标记标题左右两边的类型:图片
     */
    protected final int TITLE_TYPE_IMG = 1;
    public int statusBarHeight;
    protected Handler mHandler = new Handler();

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mActivity = (Activity) context;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        statusBarHeight = Utils.getStatusBarHeight(getActivity());
        super.onCreate(savedInstanceState);
        mInflater = LayoutInflater.from(getActivity());
    }

    @Override
    public void onDestroy() {
        dismissWaitDialog();
        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    /**
     * 全局等待对话框
     */
    public void loadWaitDialog() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                initWaitDialog();
            }
        });
    }

    private void initWaitDialog() {
        if (waitDialog == null || !waitDialog.isShowing()) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_load_wait, null);
            waitDialog = DialogUtil.getDialog(getActivity(), view);
            waitDialog.setCanceledOnTouchOutside(false);
            waitDialog.show();
        }
    }

    public void dismissWaitDialog() {
        try {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
//                    getActivity().runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
                            if (waitDialog != null && waitDialog.isShowing()) {
                                waitDialog.dismiss();
                                waitDialog = null;
                            }
//                        }
//                    });
                }
            },1000);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 需在setContentView方法之后调用. 设置后,如果不对左侧的事件进行监听,默认的点击事件是结束当前界面.
     * <p/>
     * 标题传资源id和字符串皆可.
     * <p/>
     * 如果某一侧显示的是图片,则那一侧只能传对应的图片资源id.如果是文字,则资源id和字符串皆可.
     *
     * @param title     标题
     * @param left      是否显示左侧的部分
     * @param leftType  左侧的类型
     * @param l         左侧部分内容
     * @param right     是否显示右侧的部分
     * @param rightType 右侧的类型
     * @param r         右侧部分的内容
     */
    protected void setTitle(Object title, boolean left, int leftType, Object l,
                            boolean right, int rightType, Object r) {
        try {
            rlTitle = (RelativeLayout) rootView.findViewById(R.id.rl_title);
            tvTitle = (TextView) rootView.findViewById(R.id.tv_title);
            tvLeft = (TextView) rootView.findViewById(R.id.tv_title_left);
            llLeft = (LinearLayout) rootView.findViewById(R.id.ll_title_left);
            ivLeft = (ImageView) rootView.findViewById(R.id.iv_title_left);
            tvRight = (TextView) rootView.findViewById(R.id.tv_title_right);
            ivRight = (ImageView) rootView.findViewById(R.id.iv_title_right);
            llRight = (LinearLayout) rootView.findViewById(R.id.ll_title_right);
            titleLineBottom = rootView.findViewById(R.id.line_bottom);
            if (title != null && title instanceof String) {
                if (!TextUtils.isEmpty((String) title)) {
                    tvTitle.setVisibility(View.VISIBLE);
                    tvTitle.setText((String) title);
                } else {
                    tvTitle.setVisibility(View.INVISIBLE);
                }
            } else if (title != null && title instanceof Integer) {
                if (((Integer) title) > 0) {
                    tvTitle.setVisibility(View.VISIBLE);
                    tvTitle.setText((Integer) title);
                } else {
                    tvTitle.setVisibility(View.INVISIBLE);
                }
            }
            if (left) {
                llLeft.setVisibility(View.VISIBLE);
                registerBack();
                if (leftType == TITLE_TYPE_TEXT) {
                    ivLeft.setVisibility(View.GONE);
                    tvLeft.setVisibility(View.VISIBLE);
                    if (l instanceof String) {
                        tvLeft.setText((String) l);
                    } else if (l instanceof Integer) {
                        tvLeft.setText((Integer) l);
                    }
                } else if (leftType == TITLE_TYPE_IMG) {
                    ivLeft.setVisibility(View.VISIBLE);
                    tvLeft.setVisibility(View.GONE);
                    if (l instanceof Integer) {
                        ivLeft.setImageResource((Integer) l);
                    }

                }
            } else {
                llLeft.setVisibility(View.INVISIBLE);
            }
            if (right) {
                llRight.setVisibility(View.VISIBLE);
                rightDo();
                if (rightType == TITLE_TYPE_TEXT) {
                    ivRight.setVisibility(View.GONE);
                    tvRight.setVisibility(View.VISIBLE);
                    if (r instanceof String) {
                        tvRight.setText((String) r);
                    } else if (r instanceof Integer) {
                        tvRight.setText((Integer) r);
                    }
                } else if (rightType == TITLE_TYPE_IMG) {
                    ivRight.setVisibility(View.VISIBLE);
                    tvRight.setVisibility(View.GONE);
                    if (r instanceof Integer) {
                        ivRight.setImageResource((Integer) r);
                    }
                }
            } else {
                llRight.setVisibility(View.INVISIBLE);
            }

        } catch (Exception e) {

        }
    }

    /**
     * 设置点击左上角的返回事件.默认是finish界面
     */
    protected void registerBack() {
        LinearLayout llLeft = (LinearLayout) rootView.findViewById(R.id.ll_title_left);
        llLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                leftDoWhat();
            }
        });
    }

    /**
     * 设置点击右上角的返回事件.
     */
    protected View rightDo() {
        LinearLayout llRight = (LinearLayout) rootView.findViewById(R.id.ll_title_right);
        llRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rightDoWhat();
            }
        });
        return llRight;
    }

    protected void rightDoWhat() {

    }

    protected void leftDoWhat() {
        StringUtils.hideSoftKeyboard(getActivity());
        getActivity().finish();
    }

    protected void onhttpSuccess(String data, int method) {
        dismissWaitDialog();
    }

    protected void onhttpFailed(String message, int method) {
        dismissWaitDialog();
//        if (!StringUtils.isEmpty(message)) {
//            ToastUtil.makeShortText(mActivity, message);
//        }
    }

    /**
     * [页面跳转]
     *
     * @param clz
     */
    public void startActivity(Class<?> clz) {
        startActivity(new Intent(mActivity, clz));
    }

    /**
     * 携带数据页面跳转
     *
     * @param clz
     * @param bundle
     */
    public void startActivity(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(mActivity, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }
    /**
     * 携带数据页面跳转并且有请求码
     *
     * @param cls
     * @param bundle
     * @param requestCode
     */
    public void startActivityForResult(Class<?> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(mActivity, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }
    protected Dialog dialogConfirm(String title, String content, String leftBtnName, String rightBtnName) {
        View dialogView = mInflater.inflate(R.layout.dialog_confirm, null);
        final Dialog dialog = DialogUtil.showDialogCenter(getActivity(), dialogView, 300);
        TextView tvTitle = (TextView) dialogView.findViewById(R.id.dialog_title);
        TextView tvContent = (TextView) dialogView.findViewById(R.id.dialog_content);
        TextView leftBtn = (TextView) dialogView.findViewById(R.id.dialog_left_btn);
        TextView rigntBtn = (TextView) dialogView.findViewById(R.id.dialog_right_btn);
        if (!StringUtils.isEmpty(title)) {
            tvTitle.setText(title);
        }
        if (!StringUtils.isEmpty(content)) {
            tvContent.setText(content);
            tvContent.setVisibility(View.VISIBLE);
        }
        if (!StringUtils.isEmpty(leftBtnName)) {
            leftBtn.setText(leftBtnName);
        }
        if (!StringUtils.isEmpty(rightBtnName)) {
            rigntBtn.setText(rightBtnName);
        }
        leftBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                dialogLeftBtn();
            }
        });
        rigntBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                dialogRightBtn();
            }
        });
        return dialog;
    }

    protected void dialogLeftBtn() {

    }

    protected void dialogRightBtn() {

    }

    @Override
    public void handleResult(String data, int encoding, int method) {
        switch (encoding) {
            case AnsynHttpRequest.SUCCESS_HTTP:
                try {
                    JSONObject jsonObject = new JSONObject(data);

                    if (jsonObject.has("state") && jsonObject.getInt("state") == 1) {
                        onhttpSuccess(data, method);
                    } else {
                        String message = null;
                        if (jsonObject.has("error")) {
                            message = jsonObject.getString("error");
                            onhttpFailed(message, method);
                        } else if (jsonObject.has("message")) {
                            message = jsonObject.getString("message");
                            onhttpFailed(message, method);
                        }
                        if("此账户已在其他地方登陆".equals(message)){
                            MyApplication.getInstance().sputil.put(ConstantUserInfo.ISLOGIN, false);
                            MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_ID, "");
                            Intent intent = new Intent(getActivity(), LoginActivity.class);
                            intent.putExtra("login_out", "2");
                            startActivity(intent);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    onhttpFailed(getResources().getString(R.string.response_result), method);
                }
                break;
            case AnsynHttpRequest.FAILURE_HTTP:
                try {
                    onhttpFailed(getResources().getString(R.string.response_result), method);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case AnsynHttpRequest.FAILURE_NETWORK:
                try {
                    onhttpFailed(null, method);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }
}
